package com.hskj.springboot.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class RabbitMQDlazyConfig {
    //定义交换机的名称和队列名称
    public static final String EXCHANGE_F_DELAY_NAME = "boot_delay_exchange";
    public static final String EXCHANGE_DELAY_NAME = "delay_exchange";
    public static final String QUEUE_F_DELAY_NAME = "boot_delay_queue";
    public static final String QUEUE_DELAY_NAME = "delay_queue";

    /*
    * 配置正常交换机
    * */
    @Bean("bootDelayExchange")
    public Exchange springDlxExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_F_DELAY_NAME).durable(true).build();
    }
    /*
     * 配置死信交换机
     * */
    @Bean("delayExchange")
    public Exchange springboootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_DELAY_NAME).durable(true).build();
    }
    /*
     * 配置正常队列
     * */
    @Bean("bootDelayQueue")
    public Queue springbootQueue(){
        HashMap<String, Object> dlxMap = new HashMap<>();
        //x-message-ttl 指的是过期时间(作用为延迟时间)
        dlxMap.put("x-message-ttl",10000);
        //x-dead-letter-exchange 指的是死信交换机
        dlxMap.put("x-dead-letter-exchange", RabbitMQDlazyConfig.EXCHANGE_DELAY_NAME);
        //x-dead-letter-routing-key 指的是死信routingKey
        dlxMap.put("x-dead-letter-routing-key","delay.hehe");
        return QueueBuilder.durable(QUEUE_F_DELAY_NAME).withArguments(dlxMap).build();
    }
    /*
     * 配置死信队列
     * */
    @Bean("delayQueue")
    public Queue springdlxQueue(){
        return QueueBuilder.durable(QUEUE_DELAY_NAME).build();
    }
    /*
    * 绑定正常交换机和队列
    * */
    @Bean
    public Binding QueueBindingExchange(@Qualifier("bootDelayQueue") Queue queue,@Qualifier("bootDelayExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("boot.delay.#").noargs();
    }
    /**
     *死信队列和死信交换机绑定关系
     * 1. 知道哪个队列
     * 2. 知道哪个交换机
     * 3. routing key
     *
     */
    @Bean
    public Binding bindDlxQueueExchange(@Qualifier("delayQueue") Queue queue,@Qualifier("delayExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("delay.#").noargs();
    }
}
